from django.db import models
from common.models import AccessionModel
from protocol.models import Protocol
from lab.models import Researcher
import django.contrib.localflavor.us.models as us_models
from django.core.files.storage import FileSystemStorage
from settings import FILE_DB_ROOT

class Experiment(AccessionModel):
    PATH_DEFAULT = [
        "{{ obj.protocol.path}}",
        "{{ obj.name }}",
    ]
    
    name = models.CharField(max_length=50, unique=True)
    protocol = models.ForeignKey(Protocol)
    project_leader = models.ForeignKey(Researcher)
    nih = models.BooleanField(help_text="Should we be asking NIH relevant info such as ethnicity and race?")
    sensitive = models.TextField(help_text="Details for how to handle or collect HIPAA sensitive and information like contact info", blank=True)
    details = models.TextField()
    
    def __unicode__(self):
        return self.name
    

class Race(models.Model):
    name = models.CharField(max_length=50, unique=True)
    
    def __unicode__(self):
        return self.name
    

class SubjectCode(models.Model):
    name = models.CharField(max_length=50, unique=True)
    
    def __unicode__(self):
        return self.name
    

class Subject(AccessionModel):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
        ('U', 'Unknown'),
        ('D', 'Declined')
    )
    HANDEDNESS_CHOICES = (
        ('L', 'Left'),
        ('R', 'Right'),
        ('A', 'Ambidextrous'),
        ('U', 'Unknown'),
        ('D', 'Declines'),
    )
    ETHNICITY_CHOICES = (
        ('H', 'Hispanic or Latino'),
        ('N', 'Non Hispanic or Latino'),
        ('U', 'Unknown'),
        ('D', 'Declined'),
    )
    
    PATH_DEFAULT = [
        "{{ obj.experiment.path}}",
        "{{ obj.pk }}",
    ]
    
    experiment = models.ForeignKey(Experiment)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    handedness = models.CharField(max_length=1, choices=HANDEDNESS_CHOICES)
    ethnicity = models.CharField(max_length=1, choices=ETHNICITY_CHOICES)
    race = models.ManyToManyField(Race)
    other = models.ManyToManyField("self", verbose_name="Other Subject IDs")
    codes = models.ManyToManyField(SubjectCode, verbose_name="Subject Codes")
    notes = models.TextField()
    
    def __unicode__(self):
        return self.pk
    

class Phone(models.Model):
    number = us_models.PhoneNumberField(unique=True)
    
    def __unicode__(self):
        return self.number
    

class Email(models.Model):
    email = models.EmailField(max_length=150, unique=True)
    
    def __unicode__(self):
        return self.email
    

class Contact(models.Model):
    subject = models.ForeignKey(Subject, unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=100)
    address_1 = models.CharField(max_length=200)
    address_2 = models.CharField(max_length=200)
    city = models.CharField(max_length=50)
    state = us_models.USStateField()
    zip_code = us_models.CharField(max_length=5)
    phones = models.ManyToManyField(Phone)
    emails = models.ManyToManyField(Email)
    allow_contact = models.BooleanField()
    active_date = models.DateField(help_text="How long can we keep the contact information?")
    notes = models.TextField()
    
    def __unicode__(self):
        return self.first_name + " " + self.last_name
    

class CompensationType(models.Model):
    name = models.CharField(max_length=100, unique=True)
    
    def __unicode__(self):
        return self.name
    

class CompensationSource(models.Model):
    name = models.CharField(max_length=150, unique=True)
    
    def __unicode__(self):
        return self.name
    

class Location(models.Model):
    name = models.CharField(max_length=150, unique=True)
    
    def __unicode__(self):
        return self.name
    

class SubjectSession(AccessionModel):
    PATH_DEFAULT = [
        "{{ obj.subject.path}}",
        "{{ obj.session }}",
    ]
    
    subject = models.ForeignKey(Subject)
    session = models.PositiveIntegerField(default=1)
    age = models.PositiveIntegerField()
    date_tested = models.DateField()
    time_tested = models.TimeField()
    compensation = models.DecimalField(max_digits=10, decimal_places=2)
    compensation_type = models.ForeignKey(CompensationType)
    compensation_source = models.ForeignKey(CompensationSource)
    location = models.ForeignKey(Location)
    consenter = models.ForeignKey(Researcher, related_name="session_consenter")
    consented = models.BooleanField()
    copy_consent = models.BooleanField(verbose_name='Received copy of consent?')
    completed = models.BooleanField(verbose_name='Completed the session?')
    researchers = models.ManyToManyField(Researcher)
    adverse_event = models.BooleanField(verbose_name='Injured or experienced an adverse event?', help_text='Contact PI if this is the case.')
    notes = models.TextField()
    
    def __unicode__(self):
        return self.subject.pk + " - " + self.session
    
    def clean(self, *args, **kwargs):
        if self.pk is None:
            # Find previous protocol revision if exists
            entry = SubjectSession.objects.filter(subject=self.subject).order_by('session')
            if (len(entry)>0):
                entry = entry[len(entry)-1]
                self.session = entry.session + 1
        super(models.Model, self).clean(*args, **kwargs)
    
    class Meta:
        unique_together = (('subject', 'session'),)
    


def upload_revision_file(instance, filename):
    return os.path.join(instance.subject_session.path, filename)

fs = FileSystemStorage(location=FILE_DB_ROOT)

class SubjectSessionFile(models.Model):   
    subject_session = models.ForeignKey(SubjectSession)
    details = models.CharField(max_length=200, blank=True)
    filename = models.FileField(upload_to=upload_revision_file, storage=fs)
    digest = models.CharField(max_length=255, blank=True)
    
    def __unicode__(self):
        return self.filename.name
    

